<%@page language="java" pageEncoding="utf-8"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.math.BigDecimal"%>
<%@page import="inet.util.DateProc"%>
<%@page import="inet.util.UTF8Tool"%>
<%@page import="inet.util.StringTool"%>
<%@page import="lib.db.clip.Clip"%>
<%@page import="java.util.Vector"%>
<%@page import="lib.db.clip.ClipCategory"%>
<%@page import="java.io.File"%>
<%@page import="lib.util.FileTool"%>
<%@page import="lib.db.clip.Const"%>

<jsp:useBean id="req" class="inet.util.MultipartRequest" />
<jsp:setProperty property="request" name="req" value="<%=request %>" />
<jsp:useBean id="clipDAO" class="lib.db.clip.ClipDAO" scope="session"/>
<jsp:useBean id="categoryDAO" class="lib.db.clip.ClipCategoryDAO" scope="session"/>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Cập nhật clip </title>
    <link rel="icon" href="<%=request.getContextPath() %>/favicon.ico" type="image/x-icon" />
    <link href="../include/default.css" type="text/css" rel="stylesheet"></link>
	<script src="../include/default.js" type="text/javascript"></script>  
  </head>
  <body marginheight="0" topmargin="0" marginwidth="0" leftmargin="0" rightmargin="0">
  	<%@ include file="../include/checklogin.jsp" %>
  	<div class="list" style="margin-left: 25%; min-height: 30px; padding-top: 10px; font-size: 15px;">
  		<a href="<%=request.getContextPath() %>/">Home page</a>  &raquo; 
  		Cập nhật Clip
  	</div>
  	<center>
	  	<p align="center">
			<b><font color="#000080" face="Tahoma" size="4">
				EDIT CLIP
			</font></b><br/>
			<span class="list"><font color="red">(*)</font>: Bắt buộc nhập</span>
	  	</p>
		<br/>
		<%
			String sAction = req.getStringParameter("action");
			String sClipId = req.getStringParameter("clipId");
			BigDecimal clipId = BigDecimal.ZERO;
			if(sClipId != null && StringTool.isNumberic(sClipId)) {
				clipId = new BigDecimal(sClipId);
			}
			
			String sCateId = req.getStringParameter("slbCate");
			BigDecimal cateId = BigDecimal.ZERO;
			if (sCateId != null && StringTool.isNumberic(sCateId)) {
				cateId = new BigDecimal(sCateId);
			}
			Clip file = clipDAO.getRow(clipId);
			if(file == null) {
			%>
				<script type="text/javascript">
					window.location.href = "<%=request.getContextPath() %>/message/?c=<%//=MessageShow.CONTENT_OWNER %>&b=album/index.jsp";
				</script>
			<%
				return;
			}
			String msg = "";
			//File
			String name = "";
			String fileType = "";
			InputStream inputStream = null;
			int MAX_AVATAR_SIZE = 30720; // 30kb
			int MAX_CONTENT_SIZE = 11534336; // 11mb
			byte [] bImageFile = null;
			if(req.getFileParameter("fileImageContent") != null){
				//fileName = req.getFileParameter("fileEditContent").getName();
				fileType = req.getFileParameter("fileImageContent").getType();
				//fileType = new MimetypesFileTypeMap().getContentType(fileName);
				if(fileType.substring(0,5).equalsIgnoreCase("image")){
			    	// its an image
			    	inputStream = req.getFileParameter("fileImageContent").getInputStream();
					if(inputStream != null){
						try{
				    		bImageFile = new byte[inputStream.available()];
							inputStream.read(bImageFile);
						}catch(Exception ex){}
					}
			    }
			}
			byte [] bClipFile = null;
			if(req.getFileParameter("fileClipContent") != null){
				//fileName = req.getFileParameter("fileEditContent").getName();
				fileType = req.getFileParameter("fileClipContent").getType();
				//fileType = new MimetypesFileTypeMap().getContentType(fileName);
				if(fileType.contains("3gp")){
			    	// its an image
			    	inputStream = req.getFileParameter("fileClipContent").getInputStream();
					if(inputStream != null){
						try{
				    		bClipFile = new byte[inputStream.available()];
							inputStream.read(bClipFile);
						}catch(Exception ex){}
					}
			    }
			}
			if("EDIT_FILE".equalsIgnoreCase(sAction)){
				name = req.getStringParameter("txtName");
				String sMinute = req.getStringParameter("slbMinute");
				String sSecond = req.getStringParameter("slbSecond");
				String clipLength = "";
				if(name == null || "".equals(name)) {
					msg = "<span style='color:red'>Vui lòng nhập tên clip</span>";
				} else if (cateId == BigDecimal.ZERO) {
					msg = "<span style='color:red'>Vui lòng chọn danh mục clip</span>";
				} else if ("00".equals(sMinute)) {
					msg = "<span style='color:red'>Vui lòng chọn thời gian </span>";
				} else {
					//String rootFolder = "/data/webhome/sms.vn_v2/kinhdoanh/fileactive/";
					String rootFolder = "D://clip/";
					String imgFolder = "";
                    String contentFolder = "";
					if(bImageFile != null && bImageFile.length > 0 && bImageFile.length < MAX_AVATAR_SIZE) {
						imgFolder = rootFolder+ "/img/";
	  					File directory = new File(rootFolder);
	  					if (!directory.exists())
	  						directory.mkdir();
	  					directory = new File(imgFolder);
	  					if (!directory.exists())
	  						directory.mkdir();
	  					String fileUploadName = req.getFileParameter("fileImageContent").getName();
	  					File fileImg = new File(imgFolder+fileUploadName);
	  					if (fileImg.exists()){
	  						fileUploadName = directory.listFiles().length+fileUploadName;
	  					}
						FileTool.saveToFile(bImageFile, imgFolder+fileUploadName);
	  					clipDAO.updateImageFile(file.getId(), fileUploadName);
					}
					if(bClipFile != null && bClipFile.length > 0 && bClipFile.length < MAX_CONTENT_SIZE) {
						contentFolder = rootFolder+ "/clip/";
	  					File directory = new File(rootFolder);
	  					if (!directory.exists())
	  						directory.mkdir();
	  					directory = new File(contentFolder);
	  					if (!directory.exists())
	  						directory.mkdir();
	  					String fileUploadName = req.getFileParameter("fileClipContent").getName();
	  					File fileContent = new File(contentFolder+fileUploadName);
	  					if (fileContent.exists()){
	  						fileUploadName = directory.listFiles().length+fileUploadName;
	  					}
						FileTool.saveToFile(bClipFile, contentFolder+fileUploadName);
						contentFolder = contentFolder+fileUploadName;
	  					clipDAO.updateContentFile(file.getId(), contentFolder, bClipFile.length);
					}
					clipLength = sMinute+":"+ sSecond;
					boolean isOk = clipDAO.updateRow(file.getId(), name, cateId,  Const.CLIP_STATUS_ACTIVE, clipLength);
					if(isOk){
					   msg = "<span style='color:blue'>Cập nhật thành công clip</span>";
					   file = clipDAO.getRow(clipId);
					} else {
					   msg = "<span style='color:red'>Cập nhật KHÔNG thành công clip</span>";
					}
				}
			}
			Vector vCate = categoryDAO.findAll(1, 50);
		%>
		<div align="center"><%=msg %></div><br/>
		<% 
			if(file != null) {
		%>
		<form method="post" name="frmEditFile" onsubmit="return editFile();" enctype="multipart/form-data">
			<input type="hidden" name="action" />
			<table width="50%" border="0" cellpadding="4" cellspacing="0">
				<tr height="40px">
					<td class="header" width="20%">
					 	File ảnh
					</td>
					<td> 
					  <input type="file" size="30" name="fileImageContent" value="" />
					  <img width="300px" height="200px;" src="<%= request.getContextPath() %>/clip-image/?id=<%= file.getId() %>" alt="" />
					</td>
				</tr>
				<tr height="40px">
					<td class="header" width="20%">
					 	Tên clip
					</td>
					<td>
					  <input type="text" size="30" name="txtName" value="<%= file.getName() %>" maxlength="100"/>
					</td>
				</tr>
				<tr height="40px">
					<td class="header" width="20%">
					 	Danh mục <font color="red">(*)</font>
					</td>
					<td> 
					  	 <select name="slbCate">
					  	 	<option value="-1"> Chọn danh mục </option>
					  	 <% 
					  	 	if(vCate != null && !vCate.isEmpty()) {
					  	 		ClipCategory cate = null;
					  	 		for (Iterator it = vCate.iterator(); it.hasNext(); ){
					  	 			cate = (ClipCategory) it.next();
					  	 			if(cate == null )continue;
					  	 %>
					  	 	<option <%= cate.getId().equals(file.getCateId())?"selected":"" %> value="<%= cate.getId() %>"> <%= cate.getName() %> </option>
					  	 <%
					  	 		}
					  	 	}
					  	 %>
					  	 </select>
					</td>
				</tr>
				<tr height="40px">
					<td class="header" width="20%">
					 	Độ dài clip (phút)
					</td>
					<td class="list">
					   Phút
					   <select name="slbMinute">
					       <% 
					           // Xử lý độ dài của thời gian
					           String sFileMinute = file.getClipLength().substring(0, 2);
					           String sFileSecond = file.getClipLength().substring(3, 5);
					           String sMinute = "";
					           for(int i = 0; i < 20 ; i ++) {
					               if(i < 10)sMinute = "0" + i;
					               else sMinute = "" + i;
					       %>
					       <option <%= sFileMinute.equals(sMinute) ? "selected":"" %> value="<%= sMinute %>"><%= sMinute %></option>
					       <%
					           }
					       %>
					   </select> 
					   Giây
					   <select name="slbSecond">
					       <% 
					           String sSecond = "";
					           for(int i = 0; i <= 59 ; i ++) {
					               if(i < 10)sSecond = "0" + i;
					               else sSecond = "" + i;
					       %>
					       <option <%= sFileSecond.equals(sSecond) ? "selected":"" %> value="<%= sSecond %>"><%= sSecond %></option>
					       <%
					           }
					       %>
					   </select>
					</td>
				</tr>
				<tr height="40px">
					<td class="header" width="20%">
					 	Nội dung clip
					</td>
					<td> 
					  <input type="file" size="30" name="fileClipContent" value=""/>
					</td>
				</tr>
			</table>
			<table width="50%" border="0" rules="all" cellpadding="4" cellspacing="0">
				<tr height="40px">
					<td align="center">
						<input type="submit" class="blogg-button GEE3RVNDNU" class="flatbutton" value=" Cập nhật " /> &nbsp;&nbsp;
						<input type="button" onclick="window.location.href='index.jsp';" class="blogg-button GEE3RVNDNU" class="flatbutton" value=" Quản lý ảnh " />
					</td>
				</tr>
			</table>
		</form>
		<% 
			}
		%>
    </center>
  </body>
  <script type="text/javascript">
  	function editFile(){
  		//Họ tên
  		if(frmEditFile.txtName.value == ''){
  			alert('Vui lòng nhập tên clip');
  			frmEditFile.txtName.focus();
  			return false;
  		} else if(frmEditFile.slbCate.value == '-1'){
  			alert('Vui lòng chọn danh mục');
  			frmEditFile.slbCate.focus();
  			return false;
  		} else if(frmEditFile.slbMinute.value == '00'){
  			alert('Vui lòng chọn phút của clip');
  			frmEditFile.slbMinute.focus();
  			return false;
  		}
  		
  		frmEditFile.action.value = 'EDIT_FILE';
  		frmEditFile.submit();
  	}
  	
  </script>
</html>
